package com.ycyun.admin.service.impl;

import com.ycyun.admin.dao.PermissionDao;
import com.ycyun.admin.dto.LoginUser;
import com.ycyun.admin.model.Permission;
import com.ycyun.admin.model.SysUser;
import com.ycyun.admin.model.SysUser.Status;
import com.ycyun.admin.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 哦谢特谢特
 * @Date: 2018/5/21 20:44
 * @Description: spring security登录处理
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService{


    @Autowired
    private UserService userService;
    @Autowired
    private PermissionDao permissionDao;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = userService.getUser(username);
        if (user == null) {
            throw new AuthenticationCredentialsNotFoundException("用户名不存在");
        } else if (user.getStatus() == Status.LOCKED) {
            throw new LockedException("用户被锁定，请联系管理员");
        } else if (user.getStatus() == Status.DISABLED) {
            throw new DisabledException("用户已被封禁");
        }

        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(user, loginUser);

        List<Permission> permissions = permissionDao.listByUserId(user.getId());
        loginUser.setPermissions(permissions);

        return loginUser;
    }
}
